package org.example.service;

import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.config.annotation.DubboService;
import org.example.bean.Store;

import java.util.HashMap;
import java.util.Map;

@DubboService
public class StoreServiceImpl implements StoreService {

    private static final Map<String, Store> STORE_MAP = new HashMap<>();

    static {
        STORE_MAP.put("123", Store.builder().build().setStoreId("123").setStoreName("chenwj"));
        STORE_MAP.put("456", Store.builder().build().setStoreId("456").setStoreName("hello"));
    }

    @Override
    public Store getStore(String storeId) {
        System.out.println("服务端===商店(getStore) -> " + storeId);
        Store store = STORE_MAP.get(storeId);
        System.out.println("服务端===商店===返回数据 -> " + store + "\n");
        return store;
    }

    @Override
    public void getStoresServerStream(String storeId, StreamObserver<Store> responseObserver) {
        System.out.println("服务端===商店(getStoresServerStream) -> " + storeId);
        Store store = STORE_MAP.get(storeId);
        System.out.println("服务端===商店===返回数据 -> " + store + "\n");
        responseObserver.onNext(store);
        responseObserver.onCompleted();
    }

    //1.StreamObserver接口使用了观察者模式的概念，与stream流模式完全契合，一次onnext调用代表stream内一次发送；
    // 2.对于需要接受数据的场景，Grpc框架是被观察者；对于需要发送数据的场景，Grpc框架是观察者；
    @Override
    public StreamObserver<Store> getStoresClientStream(StreamObserver<Store> responseObserver) {
        System.out.println("服务端===商店(getStoresClientStream)");
        return new StreamObserver<Store>() {
            @Override
            public void onNext(Store store) {
                // 接收客户端发送过来的数据，然后返回数据给客户端
                System.out.println("服务端===商店===onNext===接收客户端发送过来的数据 -> " + store);
                store.setStoreName("change");
                System.out.println("服务端===商店===onNext===修改数据并返回 -> " + store);
                responseObserver.onNext(store);
                responseObserver.onCompleted();
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("服务端===商店===Throwable -> " + throwable);
            }

            @Override
            public void onCompleted() {
                System.out.println("服务端===商店===接收客户端发送过来的数据完毕\n");
            }
        };
    }

}
